import type { Product } from '@/types/product'
import { defineStore } from 'pinia'
import { useUserStore } from '@/stores'
import { ref } from 'vue'
import { addCommentApi, getCommentsByProductIdApi } from '@/api/comment'
import type { CommentDTO, CommentVO } from '@/types/comment'
import { formatDateTime } from '@/utils/formatDate'
import {
  addProductCollectApi,
  deleteProductCollectApi,
  getProductIsCollectApi,
} from '@/api/productCollect'
import { getPublisherIsFollowedApi, userFollowApi } from '@/api/userFollows'
import { getProductByIdApi } from '@/api/productInfo'

// 定义单个商品详情的 store
export const useProductDetailStore = defineStore('productDetail', () => {
  // 存储商品详情
  const productDetail = ref<Product>({
    id: '',
    userId: '',
    title: '',
    intro: '',
    image: '',
    price: 0,
    originalPrice: 0,
    typeId: '',
    postType: 0,
    likeCount: 0,
    adcode: '',
    province: '',
    city: '',
    district: '',
    status: 0,
    createTime: '',
    avatar: '',
    nickName: '',
  })
  // 商品图片索引
  const imageIndex = ref<number>(0)
  // 存储评论列表
  const comments = ref<CommentVO[]>([])
  // 存储单条评论数据
  const commentDto = ref<CommentDTO>({
    productId: '',
    content: '',
    parentId: null,
    parentNickname: '',
  })
  // 标记该商品是否被收藏
  const isCollected = ref(false)

  // 标记该商品发布者是否被当前登录用户关注
  const isFollowed = ref(false)

  // 标记是否是回复评论
  const isReply = ref(false)

  // 回复评论的对象
  const replyUserNickname = ref('')

  // 切换商品图片
  const next = () => {
    imageIndex.value = (imageIndex.value + 1) % productDetail.value!.image.length
  }
  const prev = () => {
    imageIndex.value =
      (imageIndex.value - 1 + productDetail.value!.image.length) % productDetail.value!.image.length
  }

  // 从 userStore 中获取对应ID的商品信息、评论信息、是否被收藏
  const getProductDetail = async (id: string) => {
    try {
      const res = await getProductByIdApi(id)
      if (res.code === 0) {
        // 转换 createTime 格式
        productDetail.value = {
          ...res.data,
          // 将图片 URL 字符串转为数组
          image: res.data.image.split(',').map((url: string) => url.replace(/^'|'$/g, '')),
          createTime: formatDateTime(res.data.createTime),
        }
      }
    } catch (error) {
      console.error('获取商品详情失败:', error)
    }
    // 重置图片索引
    imageIndex.value = 0
    if (useUserStore().Authorization !== null) {
      // 获取商品是否被收藏
      try {
        const res = await getProductIsCollectApi(id)
        if (res.code === 0) {
          isCollected.value = res.data
        }
      } catch (error) {
        console.error('获取商品是否被收藏失败:', error)
      }
      // 获取该商品的发布者是否被当前登录用户关注
      try {
        const res = await getPublisherIsFollowedApi(productDetail.value!.userId)
        if (res.code === 0) {
          isFollowed.value = res.data
        }
      } catch (error) {
        console.error('获取发布者是否被关注失败:', error)
      }
    }

    // 获取评论数据
    try {
      const response = await getCommentsByProductIdApi(id)
      comments.value = response.data
    } catch (error) {
      console.error('获取评论数据失败:', error)
      comments.value = []
    }
  }

  // 发表评论
  const addComment = async () => {
    if (useUserStore().Authorization) {
      // 判断是否是回复评论
      if (isReply.value) {
        replyComment()
      } else {
        // 发表一级评论
        try {
          commentDto.value.productId = productDetail.value!.id
          const res = await addCommentApi(commentDto.value)
          if (res.code === 0) {
            // 重新获取评论数据
            const response = await getCommentsByProductIdApi(commentDto.value.productId)
            comments.value = response.data
            commentDto.value.content = ''
          }
        } catch (error) {
          ElMessage.error('发表评论失败')
          console.error('发表评论失败:', error)
        }
      }
    } else {
      ElMessage.warning('请先登录')
    }
  }

  // 回复评论
  const replyComment = async () => {
    if (useUserStore().Authorization && commentDto.value.content) {
      try {
        // 设置回复评论的父级评论ID和昵称
        commentDto.value.productId = productDetail.value!.id
        commentDto.value.parentNickname = replyUserNickname.value
        const res = await addCommentApi(commentDto.value)
        if (res.code === 0) {
          // 重新获取评论数据
          const response = await getCommentsByProductIdApi(commentDto.value.productId)
          comments.value = response.data
          // 重置回复评论数据
          commentDto.value.content = ''
          commentDto.value.parentId = null
          isReply.value = false
          replyUserNickname.value = ''
        }
      } catch (error) {
        ElMessage.error('回复评论失败')
        console.error('回复评论失败:', error)
      }
    } else {
      if (!commentDto.value.content) {
        ElMessage.warning('请输入回复内容')
      } else {
        ElMessage.warning('请先登录')
      }
    }
  }

  // 新增收藏
  const addProductCollect = async (productId: string) => {
    // 判断是否登录
    if (!useUserStore().Authorization) {
      ElMessage.warning('请先登录')
      return
    }
    try {
      const res = await addProductCollectApi(productId)
      if (res.code === 0) {
        ElMessage.success('收藏成功')
        isCollected.value = true
      }
    } catch (error) {
      ElMessage.error('收藏失败')
      console.error('收藏失败:', error)
    }
  }

  // 删除收藏
  const deleteProductCollect = async (productId: string) => {
    // 判断是否登录
    if (!useUserStore().Authorization) {
      ElMessage.warning('请先登录')
      return
    }
    try {
      const res = await deleteProductCollectApi(productId)
      if (res.code === 0) {
        ElMessage.success('取消收藏成功')
        isCollected.value = false
      }
    } catch (error) {
      ElMessage.error('取消收藏失败')
      console.error('取消收藏失败:', error)
    }
  }

  // 新增关注或者取消关注
  const addFollow = async (followUserId: string, isFollow: boolean) => {
    // 判断是否登录
    if (!useUserStore().Authorization) {
      ElMessage.warning('请先登录')
      return
    }
    try {
      const res = await userFollowApi(followUserId, isFollow)
      if (res.code === 0) {
        ElMessage.success(isFollow ? '关注成功' : '取消关注成功')
        isFollowed.value = isFollow
      }
    } catch (error) {
      console.error('获取发布者是否被关注失败:', error)
    }
  }
  // 清空回复评论数据
  const clearReplyComment = () => {
    commentDto.value.content = ''
    commentDto.value.parentId = null
    isReply.value = false
    replyUserNickname.value = ''
  }
  // 重置方法
  const resetStore = () => {
    productDetail.value = {
      id: '',
      userId: '',
      title: '',
      intro: '',
      image: '',
      price: 0,
      originalPrice: 0,
      typeId: '',
      postType: 0,
      likeCount: 0,
      adcode: '',
      province: '',
      city: '',
      district: '',
      status: 0,
      createTime: '',
      avatar: '',
      nickName: '',
    }
    imageIndex.value = 0
    comments.value = []
    commentDto.value = {
      productId: '',
      content: '',
      parentId: null,
      parentNickname: '',
    }
    isCollected.value = false
    isFollowed.value = false
    isReply.value = false
    replyUserNickname.value = ''
  }

  return {
    productDetail,
    comments,
    commentDto,
    isReply,
    replyUserNickname,
    isCollected,
    isFollowed,
    getProductDetail,
    next,
    prev,
    addComment,
    replyComment,
    clearReplyComment,
    addProductCollect,
    deleteProductCollect,
    addFollow,
    resetStore,
    imageIndex,
  }
})
